package plugin.redis;

import play.Play;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by zqx on 16/3/3.
 */
public class RedisDataSource {

    private static boolean DEBUG;
    private static String HOST;
    private static int PORT;
    private static int MAX_ACTIVE;
    private static int MAX_WAIT;
    private static int MAX_IDEL;
    private static int TIMEOUT;

    private static JedisPool jedisPool = null;
    private static JedisPoolConfig config = null;

    /**
     * 初始化Redis连接池
     */
    static {
        try {
            DEBUG = Boolean.parseBoolean(Play.configuration.getProperty("redis.debug"));
            HOST = Play.configuration.getProperty("redis.host");
            PORT = Integer.parseInt(Play.configuration.getProperty("redis.port"));
            if (DEBUG) {
                HOST = Play.configuration.getProperty("redis.debug.host");
                PORT = Integer.parseInt(Play.configuration.getProperty("redis.debug.port"));
            }
            MAX_ACTIVE = Integer.parseInt(Play.configuration.getProperty("redis.pool.maxActive"));
            MAX_WAIT = Integer.parseInt(Play.configuration.getProperty("redis.pool.maxWait"));
            MAX_IDEL = Integer.parseInt(Play.configuration.getProperty("redis.pool.maxIdle"));
            TIMEOUT = Integer.parseInt(Play.configuration.getProperty("redis.pool.timeout"));

            config = new JedisPoolConfig();
            config.setMaxActive(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDEL);
            config.setMaxWait(MAX_WAIT);
            config.setTestOnBorrow(true);
            jedisPool = new JedisPool(config, HOST, PORT, TIMEOUT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param @param jedis
     * @return void
     * @throws
     * @Title: release
     * @Description: 释放连接
     */
    public static void release(Jedis jedis) {
        jedisPool.returnResource(jedis);
    }

    public static Jedis getJedis() {
        return jedisPool.getResource();
    }
}